package com.ynet.middleground.contract.model;

import java.time.LocalDateTime;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.contract.bean.EnterpriseBaseReqObj;
import com.ynet.middleground.contract.constant.SignServerEnum;
import com.ynet.middleground.contract.dao.ServiceRecordMapper;
import com.ynet.middleground.contract.entity.ServiceRecord;
import com.ynet.middleground.user.dto.UserBaseInformationDto;
import com.ynet.middleground.user.dto.UserInfoDto;

/**
 * @author liulx
 * @description 合约签署服务记录业务模块
 * @date 2020-04-14 16:38
 */
@Component
public class ServiceRecordModel extends ServiceImpl<ServiceRecordMapper, ServiceRecord> {

    @Autowired
    UserCenterModel userCenterModel;

    /**
     * 插入调用服务签署日志
     * 
     * @param record 记录对象，客户名称、账号、统计次数该方法会自动获取计算
     * @param signServerEnum 签名服务分类枚举对象
     * @param req 带所属企业机构 id 基础请求信息
     */
    public void insertServiceRecord(ServiceRecord record, SignServerEnum signServerEnum, EnterpriseBaseReqObj req) {
        record.setServiceProvider(signServerEnum.getServerProvider());
        record.setServiceName(signServerEnum.getServerName());
        record.setGmtCreate(LocalDateTime.now());
        record.setCreateBy(req.getOperationUserId());
        record.setGmtModified(LocalDateTime.now());
        record.setModifiedBy(req.getOperationUserId());
        record.setChannel(req.getChannel());

        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(),
            "调用用户中心查询用户信息, start time: {}, req: {}", System.currentTimeMillis(), req);
        // 查询用户账号信息, 若是上传的用户不存在，则不记录用户名和账号字段，适用于仅对接签章业务的场景
        UserInfoDto userInfo = userCenterModel.getUserInfoSource(req.getOperationUserId(), req.getChannel(),
            req.getOperationUserId(), req.getEnterpriseId());
        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(),
            "调用用户中心查询用户信息, end time: {}, resp: {}", System.currentTimeMillis(), userInfo);

        // 查询到用户则根据用户账号统计，否则统计直接记录为 1
        if (userInfo != null && userInfo.getUserBaseInformationDto() != null) {
            UserBaseInformationDto userBaseInformationDto = userInfo.getUserBaseInformationDto();
            String userAccount = userBaseInformationDto.getUserAccounts();
            record.setOperatorAccount(userAccount);
            record.setOperatorName(userBaseInformationDto.getUserName());
            QueryWrapper<ServiceRecord> queryWrapper = new QueryWrapper<>();
            // 查询该用户到该类型累计次数
            queryWrapper.select("max(totalize) totalize").eq("operator_account", userAccount).eq("service_name",
                record.getServiceName());
            IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "查询用户累计次数, start time: {}",
                System.currentTimeMillis());
            Map<String, Object> resultMap = this.getMap(queryWrapper);
            IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "查询用户累计次数, end time: {}",
                System.currentTimeMillis());
            if (resultMap != null && resultMap.containsKey("totalize")) {
                int totalize = Integer.parseInt(String.valueOf(resultMap.get("totalize")));
                record.setTotalize(totalize + 1);
            } else {
                record.setTotalize(1);
            }
        } else {
            record.setTotalize(1);
        }

        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "签章落库记录, start time: {}",
            System.currentTimeMillis());
        this.save(record);
        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "签章落库记录, end time: {}",
            System.currentTimeMillis());
    }

}
